import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';

import '../../function/routes/app_route_manager.dart';

/// 视频资源类型
enum VideoResourceType {
  network, // 网络视频
  asset, // 项目资源文件
  local, // 本地文件
}

/// 视频播放页面
class VideoPlayerPage extends StatefulWidget {
  final String videoUrl;
  final VideoResourceType? videoType; // 可选，如果不提供则自动检测

  const VideoPlayerPage({super.key, required this.videoUrl, this.videoType});

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  VideoPlayerController? _videoController;
  ChewieController? _chewieController;
  bool _isInitialized = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  /// 检测视频资源类型
  VideoResourceType _detectVideoType(String videoUrl) {
    if (widget.videoType != null) {
      return widget.videoType!;
    }

    // 自动检测
    if (videoUrl.startsWith('http://') || videoUrl.startsWith('https://')) {
      return VideoResourceType.network;
    } else if (videoUrl.startsWith('assets/')) {
      return VideoResourceType.asset;
    } else {
      return VideoResourceType.local;
    }
  }

  /// 初始化视频播放器
  void _initializeVideo() {
    final videoType = _detectVideoType(widget.videoUrl);

    try {
      switch (videoType) {
        case VideoResourceType.network:
          _videoController = VideoPlayerController.networkUrl(
            Uri.parse(widget.videoUrl),
          );
          break;
        case VideoResourceType.asset:
          _videoController = VideoPlayerController.asset(widget.videoUrl);
          break;
        case VideoResourceType.local:
          _videoController = VideoPlayerController.file(File(widget.videoUrl));
          break;
      }

      _videoController!
          .initialize()
          .then((_) {
            if (mounted) {
              setState(() {
                _isInitialized = true;
              });

              // 创建 Chewie 控制器
              _chewieController = ChewieController(
                videoPlayerController: _videoController!,
                autoPlay: true,
                looping: false,
                allowFullScreen: true,
                allowMuting: true,
                showOptions: true,
                showControlsOnInitialize: false,
                materialProgressColors: ChewieProgressColors(
                  playedColor: const Color(0xFFFF8A3C),
                  handleColor: const Color(0xFFFF8A3C),
                  backgroundColor: Colors.white.withOpacity(0.1),
                  bufferedColor: Colors.white.withOpacity(0.3),
                ),
                placeholder: Center(
                  child: CircularProgressIndicator(
                    color: const Color(0xFFFF8A3C),
                  ),
                ),
                autoInitialize: true,
              );

              // 自动播放
              _videoController!.play();
            }
          })
          .catchError((error) {
            if (mounted) {
              setState(() {
                _errorMessage = '视频加载失败: ${error.toString()}';
              });
            }
          });
    } catch (error) {
      if (mounted) {
        setState(() {
          _errorMessage = '视频初始化失败: ${error.toString()}';
        });
      }
    }
  }

  @override
  void dispose() {
    _chewieController?.dispose();
    _videoController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 视频播放器或状态显示
          if (_errorMessage != null)
            // 错误状态
            Positioned.fill(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline, color: Colors.red, size: 64.w),
                    SizedBox(height: 16.h),
                    Text('Video Error')
                        .fontSize(18.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w600),
                    SizedBox(height: 8.h),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 32.w),
                      child: Text(_errorMessage!)
                          .fontSize(14.sp)
                          .textColor(Colors.white.withOpacity(0.7))
                          .fontWeight(FontWeight.w400)
                          .textAlignment(TextAlign.center),
                    ),
                    SizedBox(height: 24.h),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _errorMessage = null;
                          _isInitialized = false;
                        });
                        _initializeVideo();
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 24.w,
                          vertical: 12.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFFF8A3C),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Text('Retry')
                            .fontSize(14.sp)
                            .textColor(Colors.white)
                            .fontWeight(FontWeight.w600),
                      ),
                    ),
                  ],
                ),
              ),
            )
          else if (_isInitialized && _chewieController != null)
            // 视频播放器
            Positioned.fill(child: Chewie(controller: _chewieController!))
          else
            // 加载中状态
            Positioned.fill(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(color: const Color(0xFFFF8A3C)),
                    SizedBox(height: 16.h),
                    Text('Loading Video...')
                        .fontSize(16.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w500),
                  ],
                ),
              ),
            ),

          // 顶部返回按钮
          Positioned(
            top: 0,
            left: 0,
            child: SafeArea(
              child: Padding(
                padding: EdgeInsets.all(16.w),
                child: GestureDetector(
                  onTap: () => AppRouteManager.goBack(),
                  child: Container(
                    width: 40.w,
                    height: 40.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.chevron_left,
                      color: Colors.white,
                      size: 26.w,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
